package EWCore.Utilities
{
	import EWCore.Utilities.ExpressionCalculator.*;
	
	import flash.net.ObjectEncoding;
	import flash.net.registerClassAlias;
	import flash.utils.ByteArray;
	import flash.utils.describeType;
	import flash.utils.getDefinitionByName;
	public class Useful
	{
		public static function Random(min:Number, max:Number):Number {
			if(min==max)
				return min;
			var randomNum:Number = Math.floor(Math.random() * (max - min + 1)) + min;
			return randomNum;
		}
		public static function RandomByRange(range:Range):Number {
			if(range.m_Max==range.m_Min)
				return range.m_Max;
			var randomNum:Number = Math.floor(Math.random() * (range.m_Max - range.m_Min + 1)) + range.m_Min;
			return randomNum;
		}
		public static function Randomf(min:Number, max:Number):Number {
			if(min==max)
				return min;
			var randomNum:Number = (Math.random() * (max - min)) + min;
			return randomNum;
		}
		public static function RandomfByRange(range:Range):Number {
			if(range.m_Max==range.m_Min)
				return range.m_Max;
			var randomNum:Number = (Math.random() * (range.m_Max - range.m_Min)) + range.m_Min;
			return randomNum;
		}
		
		public static function CalcExpression(i_Expression:String,i_Tags:Array=null, i_Vals:Array=null):Number
		{
			i_Expression = i_Expression.replace("\n").replace("\r").replace(" ");
			if(i_Tags==null || i_Vals==null)
			{
				i_Tags=[];
				i_Vals=[];
			}
			var mpExp:MathParser = new MathParser(i_Tags);
			var compobjExp:CompiledObject = mpExp.doCompile(i_Expression);
			if (compobjExp.errorStatus == 1)
			{
				trace(compobjExp.errorMes);
				return 0;
			}
			else
				return (mpExp.doEval(compobjExp.PolishArray, i_Vals));
		}
		
		public static function ObjectToInstance( object:Object, clazz:Class ):*
		{
			var bytes:ByteArray = new ByteArray();
			bytes.objectEncoding = ObjectEncoding.AMF0;
			
			var objBytes:ByteArray = new ByteArray();
			objBytes.objectEncoding = ObjectEncoding.AMF0;
			objBytes.writeObject( object );
			
			var typeInfo:XML = describeType( clazz );
			var fullyQualifiedName:String = typeInfo.@name.toString().replace( /::/, "." );
			registerClassAlias( fullyQualifiedName, clazz );
			
			var len:int = fullyQualifiedName.length;
			bytes.writeByte( 0x10 );
			bytes.writeUTF( fullyQualifiedName );
			bytes.writeBytes( objBytes, 1 );
			bytes.position = 0;
			var result:* = bytes.readObject();
			return result;
		}
	}
}